/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package aso.upna.threads;

import aso.upna.config.ClientConfig;
import aso.upna.information.StreamInfo;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.SocketException;
import java.net.SocketTimeoutException;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
 *
 * @author triki
 */
public class UdpStream implements Runnable
{

    private ClientConfig conf;
    private StreamInfo s_info;

    public UdpStream(ClientConfig cfg)
    {
        conf = cfg;
        s_info = null;
    }

    public UdpStream(ClientConfig cfg,StreamInfo info)
    {
        conf = cfg;
        s_info = info;
    }

    public void registerStreamInfo(StreamInfo info)
    {
        s_info = info;
    }

    public void run()
    {
        try
        {
            FileOutputStream fo = new FileOutputStream(conf.getPathToTempFile());
            DatagramSocket s = conf.getDatagramSocket();
            int data_size = conf.getDatagramSize();
            DatagramPacket dp = new DatagramPacket(new byte[data_size],data_size);
            System.out.println("Socket UDP a la espera");
            System.out.println("local port: "+s.getLocalPort());
            System.out.println("tmp file: "+conf.getPathToTempFile());

            int size = data_size;
           
            s.receive(dp);
            
            fo.write(dp.getData());
            s.setSoTimeout(3000);
           
            if(s_info!=null)
                s_info.setCurrentSize(size);

            System.out.println("Comienza a recibir");
            
            try
            {
                while(dp.getLength() > 0)
                {
                    s.receive(dp);
                    fo.write(dp.getData());
                    size+=data_size;
                    
                    if(s_info!=null)
                        s_info.setCurrentSize(size);
                }
            }
            catch(SocketTimeoutException ex){}
            finally
            {
                System.out.println("Fujo UDP terminado :: size = "+size);
                s.setSoTimeout(0);
                fo.close();
            }

        } catch (IOException ex) {
            Logger.getLogger(UdpStream.class.getName()).log(Level.SEVERE, null, ex);
        }

    }

}
